<?php
declare (strict_types = 1);

namespace app\common\service;

use app\admin\model\OperationLog as OperationLogModel;
use think\Session;

/**
 * 操作日志服务
 * Class OperationLogService
 * @package app\common\service
 */
class OperationLogService
{
    /**
     * 记录操作日志
     * @param string $operation 操作类型
     * @param string $targetType 目标类型
     * @param string $targetId 目标ID
     * @param string $content 内容
     * @param int $status 状态 1成功 0失败
     * @return bool
     */
    public static function log($operation, $targetType, $targetId = '', $content = '', $status = 1)
    {
        try {
            $adminId = Session::get('admin_id');
            $adminName = Session::get('admin_info.username') ?: '未知用户';
            
            $log = new OperationLogModel();
            $log->operator_id = $adminId ?: 0;
            $log->operator = $adminName;
            $log->operation = $operation;
            $log->target_type = $targetType;
            $log->target_id = $targetId;
            $log->content = $content;
            $log->ip_address = request()->ip();
            $log->user_agent = request()->server('HTTP_USER_AGENT');
            $log->status = $status;
            $log->created_at = date('Y-m-d H:i:s');
            
            return $log->save();
        } catch (\Exception $e) {
            // 记录日志失败不应影响正常业务
            return false;
        }
    }
    
    /**
     * 获取今日统计
     * @return array
     */
    public static function getTodayStats()
    {
        $today = date('Y-m-d');
        $startTime = $today . ' 00:00:00';
        $endTime = $today . ' 23:59:59';
        
        try {
            // 总操作数
            $total = OperationLogModel::where('created_at', 'between', [$startTime, $endTime])->count();
            
            // 成功操作数
            $success = OperationLogModel::where('created_at', 'between', [$startTime, $endTime])
                ->where('status', 1)
                ->count();
            
            // 失败操作数
            $failed = OperationLogModel::where('created_at', 'between', [$startTime, $endTime])
                ->where('status', 0)
                ->count();
            
            // 操作人数
            $operators = OperationLogModel::where('created_at', 'between', [$startTime, $endTime])
                ->distinct(true)
                ->field('operator_id')
                ->count();
            
            return [
                'total' => $total,
                'success' => $success,
                'failed' => $failed,
                'operators' => $operators
            ];
        } catch (\Exception $e) {
            return [
                'total' => 0,
                'success' => 0,
                'failed' => 0,
                'operators' => 0
            ];
        }
    }
}